package com.cjh.wechat.core.controller;

import java.util.List;
import javax.annotation.Resource;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import com.cjh.wechat.commom.pojo.Friend;
import com.cjh.wechat.commom.pojo.User;
import com.cjh.wechat.commom.type.MessType;
import com.cjh.wechat.commom.vo.InsertFriendVo;
import com.cjh.wechat.core.service.FriendService;
import com.cjh.wechat.core.service.UserService;

@Controller
@RequestMapping("/friend")
public class FriendController
{
    @Resource
    private FriendService friendService;
    @Resource
    private UserService   userService;
    
    @ResponseBody
    @RequestMapping(value = "/inviteFriend", method = RequestMethod.POST)
    public String inviteFriend(String uid, String gid)
    {
        friendService.inviteFriend(uid, gid);
        return "success";
    }
    
    @ResponseBody
    @RequestMapping(value = "/inviteFriendList", method = RequestMethod.POST)
    public List<User> inviteFriendList(String uid, String gid)
    {
        return friendService.inviteFriendList(uid, gid);
    }
    
    @ResponseBody
    @RequestMapping(value = "/moveFriend", method = RequestMethod.POST)
    public InsertFriendVo moveFriend(String id, String friendId, Integer tno)
    {
        friendService.updateByPrimaryKeySelective(id, friendId, tno);
        User user = userService.findById(friendId);
        InsertFriendVo insertFriendVo = buildInsertFriendVo(user, tno);
        return insertFriendVo;
    }
    
    @ResponseBody
    @RequestMapping(value = "/addFriend", method = RequestMethod.POST)
    public InsertFriendVo addFriend(String id, String friendId)
    {
        User user = userService.findById(friendId);
        Friend friend = friendService.findByUidAndFid(id, friendId);
        InsertFriendVo insertFriendVo = buildInsertFriendVo(user, friend.getTno());
        return insertFriendVo;
    }
    
    @ResponseBody
    @RequestMapping(value = "/delFriend", method = RequestMethod.POST)
    public String delFriend(String id, String friendId)
    {
        friendService.delFriend(id, friendId);
        return "success";
    }
    
    private InsertFriendVo buildInsertFriendVo(User user, Integer tno)
    {
        InsertFriendVo vo = new InsertFriendVo();
        vo.setAvatar(user.getAvatar());
        vo.setGroupid(tno);
        vo.setId(user.getId());
        vo.setSign(user.getSign());
        vo.setType(MessType.FRIEND.value);
        vo.setUsername(user.getUsername());
        vo.setStatus(user.getStatus());
        return vo;
    }
}
